package services

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/golang-module/carbon/v2"
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"sync"
	"sync/atomic"
)

type AutoCreateMatchRoom struct {
	lastId int64
	rds    redis.UniversalClient
	limit  chan struct{}
}

var autoCreateInstance *AutoCreateMatchRoom
var autoOnce sync.Once

func NewAutoCreateMatchRoom() *AutoCreateMatchRoom {
	autoOnce.Do(func() {
		autoCreateInstance = &AutoCreateMatchRoom{
			rds:   global2.GetRds(),
			limit: make(chan struct{}, 30),
		}
	})
	return autoCreateInstance
}
func (a *AutoCreateMatchRoom) genAutoCreateKey() string {
	return fmt.Sprintf("auto_create_room:%s", carbon.Now().ToDateString())
}

func (a *AutoCreateMatchRoom) genField(matchId, sportId int) string {
	return fmt.Sprintf("%d:%d", matchId, sportId)
}

// createMatchRoom 按照赛程来写入房间
func (a *AutoCreateMatchRoom) createMatchRoom(matchId, sportId int) {
	global2.Log.Debugf("createMatchRoom,matchId:%d,sportId:%d", matchId, sportId)
	key := a.genAutoCreateKey()
	field := a.genField(matchId, sportId)
	if a.rds.HExists(key, field).Val() {
		return
	}
	groupId := cast.ToString(matchId)
	r := imsdk2.CreateGroupRequest{
		GroupID: groupId,
		Name:    groupId,
	}
	create := imsdk2.GetSdk().CreateGroup(r)
	global2.Log.Debugf("createMatchRoom：%v", create)
	if create {
		a.rds.HSetNX(key, field, sportId)
		a.rds.ExpireAt(key, carbon.Now().EndOfDay().Carbon2Time())
	}
}

func (a *AutoCreateMatchRoom) getMatchIds(id int64) []models_sports.MatchTempSchedule {
	records := make([]models_sports.MatchTempSchedule, 0)

	startTime := carbon.Now().StartOfDay().Timestamp()
	endTime := carbon.Now().AddDays(3).EndOfDay().Timestamp()
	err := global2.Sport().Model(records).
		Select("id, match_id, sport_id").
		Where("id > ?", id).
		Where("match_time >= ? and match_time <= ?", startTime, endTime).
		Limit(200).
		Order("id asc").Find(&records).Error
	if err != nil {
		global2.Log.Errorf("find error:%v", err)
		return nil
	}
	return records
}

func (a *AutoCreateMatchRoom) SyncRoom() {
	wg := sync.WaitGroup{}
	records := a.getMatchIds(a.lastId)
	if len(records) == 0 {
		atomic.StoreInt64(&a.lastId, 0)
		return
	}
	for _, record := range records {
		atomic.StoreInt64(&a.lastId, int64(record.Id))
	}
	for _, record := range records {
		wg.Add(1)
		a.limit <- struct{}{}
		go func(item models_sports.MatchTempSchedule) {
			defer wg.Done()
			a.createMatchRoom(item.MatchId, item.SportId)
			<-a.limit
		}(record)
	}

	if len(records) < 200 {
		atomic.StoreInt64(&a.lastId, 0)
	}
	wg.Wait()
}
